/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *swapPairs(ListNode *head) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
      if (head == NULL || head->next == NULL) {
        return head;
      }

      ListNode *newHead = NULL;
      ListNode *cur = head;
      ListNode *pre = NULL;

      while (cur && cur->next) {
        ListNode *nxt = cur->next;
        cur->next = nxt->next;
        nxt->next = cur;
        if (pre) {
          pre->next = nxt;
        } else {
          newHead = nxt;
        }
        pre = cur;
        cur = cur->next;
      }

      return newHead;
    }
};
